/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, 
including commercial applications, and to alter it and redistribute it freely, 
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#include "SDFCollisionAlgorithm.h"
#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
#include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
#include <BulletCollision/CollisionShapes/btTriangleMeshShape.h>
#include <osgbCollision/Utils.h>
#include <iostream>
#include <OpenTissueFunction.h>
#include <btBulletDynamicsCommon.h>
#include <SDFManager.h>
#include <FileSystem.h>
#include <SDFContact.h>

SDFCollisionAlgorithm::SDFCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* col0Wrap,const btCollisionObjectWrapper* col1Wrap)
    : btActivatingCollisionAlgorithm(ci,col0Wrap,col1Wrap),
      m_ownManifold(false),
      m_manifoldPtr(mf)
{
    if (!m_manifoldPtr)
    {
        m_manifoldPtr = m_dispatcher->getNewManifold(col0Wrap->getCollisionObject(),col1Wrap->getCollisionObject());
        m_ownManifold = true;
    }
}

SDFCollisionAlgorithm::~SDFCollisionAlgorithm()
{
    if (m_ownManifold)
    {
        if (m_manifoldPtr)
            m_dispatcher->releaseManifold(m_manifoldPtr);
    }
}

void SDFCollisionAlgorithm::processCollision (const btCollisionObjectWrapper* col0Wrap,const btCollisionObjectWrapper* col1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
    (void)dispatchInfo;

    //std::cout<<"SDFCollisionAlgorithm::processCollision"<<std::endl;


    if (!m_manifoldPtr)
        return;

    resultOut->setPersistentManifold(m_manifoldPtr);

    btTriangleMeshShape* meshShape0 = (btTriangleMeshShape*)col0Wrap->getCollisionShape();
    btTriangleMeshShape* meshShape1 = (btTriangleMeshShape*)col1Wrap->getCollisionShape();

    //std::cout<<"SDFCollisionAlgorithm::processCollision meshShape0="<<meshShape0<<"  meshShape1="<<meshShape1<<std::endl;

    osg::Matrix m1 = osgbCollision::asOsgMatrix(col0Wrap->getWorldTransform());
    osg::Matrix m2 = osgbCollision::asOsgMatrix(col1Wrap->getWorldTransform());

    //std::cout<<"SDFCollisionAlgorithm::processCollision m1Trans="<<m1.getTrans().x()<<","<<m1.getTrans().y()<<","<<m1.getTrans().z()<<std::endl;
    //std::cout<<"SDFCollisionAlgorithm::processCollision m2Trans="<<m2.getTrans().x()<<","<<m2.getTrans().y()<<","<<m2.getTrans().z()<<std::endl;

    int sdfPtr1 = SDFManager::instance()->getPtr( (int)col0Wrap->getCollisionObject() );
    int sdfPtr2 = SDFManager::instance()->getPtr( (int)col1Wrap->getCollisionObject() );

    osg::ref_ptr<SDF> sdf1 = SDFManager::instance()->getSDF(sdfPtr1);
    osg::ref_ptr<SDF> sdf2 = SDFManager::instance()->getSDF(sdfPtr2);

    //if(sdf1->getBoxSize() < sdf2->getBoxSize())
    //{
    //    osg::ref_ptr<SDF> sdfTemp = sdf1;
    //    sdf1 = sdf2;
    //    sdf2 = sdfTemp;
    //}

    int contactPointCount = 0;

    if(sdf1.get() != NULL && sdf2.get() != NULL && sdf1->getCollisionEnable() && sdf2->getCollisionEnable())
    {
        osg::ref_ptr<SDFContact> sdfContacts = new SDFContact;
        sdfContacts->setSDF1(sdf1);
        sdfContacts->setSDF2(sdf2);

        sdf1->setMatrix(m1);
        sdf2->setMatrix(m2);
        //osg::Vec3 point = sdf2->getPointCoordinateInWorldFrame(0);
        //std::cout<<"SDFCollisionAlgorithm::processCollision point ="<<point.x()<<","<<point.y()<<","<<point.z()<<std::endl;
        //bool chargedResult = sdf1->isPointInGridInWordFrame(point.x(), point.y(), point.z());
        std::vector<osg::Vec3> pointsInside;
        osg::Vec3 contactNoraml;
        btScalar dist;
        osg::Vec3 point;

        for(int i = 0 ; i < sdf2->getPointCount(); i++)
        {
            point = sdf2->getPointCoordinateInWorldFrame(i);
            if( sdf1->isPointInGridInWorldFrame(point.x(), point.y(), point.z()) &&
                    sdf1->isPointClosedInWorldFrame(point.x(), point.y(), point.z()) &&
                    sdf1->isPointNearSharpEdgeInWorldFrame(point.x(), point.y(), point.z()) == false)
            {
                //std::cout<<"SDFCollisionAlgorithm::processCollision point ="<<point.x()<<","<<point.y()<<","<<point.z()<<std::endl;
                pointsInside.push_back(point);

                contactNoraml = sdf1->getGradientByPositionInWorldFrame(point.x(), point.y(), point.z());
//                osg::Vec3 sdf1Normal = sdf1->getGradientByPositionInWorldFrame(point.x(), point.y(), point.z());
//                osg::Vec3 sdf2Normal = sdf2->getGradientByPositionInWorldFrame(point.x(), point.y(), point.z());
//                contactNoraml = sdf1Normal - sdf2Normal;

                contactNoraml.normalize();
                contactPointCount++;

                sdfContacts->addContactPoint(point, contactNoraml);
            }
        }
        //FileSystem::instance()->saveVec3VectorToOSGFile("tempFiles/pointsInside.ive", pointsInside);
        if(sdfContacts->getContactPointsCount() > 0)
        {
            SDFManager::instance()->addSDFContact(sdfContacts);
        }
    }

//    std::cout<<"SDFCollisionAlgorithm::processCollision getNumContacts="<<resultOut->getPersistentManifold()->getNumContacts()<<std::endl;
//    std::cout<<"SDFCollisionAlgorithm::processCollision getContactBreakingThreshold="<<resultOut->getPersistentManifold()->getContactBreakingThreshold()<<std::endl;
//    std::cout<<"SDFCollisionAlgorithm::processCollision getContactProcessingThreshold="<<resultOut->getPersistentManifold()->getContactProcessingThreshold()<<std::endl;






    ///distance (negative means penetration)
//    btScalar dist = -0.2;
//    btVector3 normalOnSurfaceB(1,0,0);
//    btVector3 pos1 = col1Wrap->getWorldTransform().getOrigin();
//    /// report a contact. internally this will be kept persistent, and contact reduction is done
//    resultOut->addContactPoint(normalOnSurfaceB,pos1,dist);

    return;
}

btScalar SDFCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* col0,btCollisionObject* col1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
    (void)col0;
    (void)col1;
    (void)dispatchInfo;
    (void)resultOut;

    //not yet
    return btScalar(1.);
}
